package com.yao.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.config.BusinessException;
import com.yao.mall.model.dto.CarouselRequest;
import com.yao.mall.model.entity.Carousel;
import com.yao.mall.model.vo.CarouselVO;
import com.yao.mall.service.CarouselService;
import com.yao.mall.mapper.CarouselMapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author jiahua.yao
 * @description 针对表【carousel】的数据库操作Service实现
 * @date 2024-03-19 16:01:23
 */
@Service
public class CarouselServiceImpl extends ServiceImpl<CarouselMapper, Carousel>
        implements CarouselService {
    @Resource
    private CarouselMapper carouselMapper;

    @Override
    public List<CarouselVO> getCarousel(Integer site) {
        //选取轮播图的规则:首先启用，其次降序，最后选5个展示
        QueryWrapper<Carousel> carouselQueryWrapper = new QueryWrapper<>();
        carouselQueryWrapper.eq("is_enable", 0)
                .eq("site",site)
                .orderBy(true, false, "sort_order")
                .last("limit 5");
        List<Carousel> list = carouselMapper.selectList(carouselQueryWrapper);
        List<CarouselVO> carouselVOList = list.stream().map(carousel -> {
            CarouselVO carouselVO = new CarouselVO();
            BeanUtils.copyProperties(carousel, carouselVO);
            return carouselVO;
        }).toList();
        return carouselVOList;
    }

    @Override
    public Boolean addCarousel(CarouselRequest carouselRequest) {
        //1.非空判断
        check(carouselRequest);
        //2.add
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(carouselRequest, carousel);
        return this.save(carousel);
    }

    private static void check(CarouselRequest carouselRequest) {
        if (StringUtils.isAnyBlank(carouselRequest.getImageUrl(),
                carouselRequest.getLink())|| carouselRequest.getSortOrder() == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "必要参数不能为空");
        }
        if(carouselRequest.getSite() == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请输入轮播图显示位置");
        }
    }

    @Override
    public Boolean deleteCarousel(Long id) {
        int i = carouselMapper.deleteById(id);
        return i > 0;
    }

    @Override
    public Boolean updateCarousel(CarouselRequest carouselRequest) {
        check(carouselRequest);
        if (carouselRequest.getId() == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "商品图片id为空");
        }
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(carouselRequest, carousel);
        return this.updateById(carousel);
    }
}




